package com.sunch.controller;

import com.sunch.pojo.Home;
import com.sunch.pojo.Room;
import com.sunch.pojo.User;
import com.sunch.properties.JwtProperties;
import com.sunch.service.UserService;
import com.sunch.utils.JwtUtil;
import com.sunch.utils.Result;
import com.sunch.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        log.info("用户注册：{}",user.getUsername());
        return userService.register(user);
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        log.info("用户登录：{}",user.getUsername());
        User u = userService.login(user);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", u.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );
        return u != null?Result.success(token):Result.error("用户名或密码错误");
    }

    /**
     * 用户添加家庭
     * @param
     * @return
     */
    @PostMapping("/addHome")
    public Result<Home> addHome(@RequestBody Home home) {
        home.setUserId(UserHolder.getUser().getId());
        return userService.addHome(home);
    }

    /**
     * 查询当前用户所有的家
     * @return
     */
    @GetMapping("/getHome")
    public Result<List<Home>> getHome(){
        //获取该登录用户的主键id
        int UserId = UserHolder.getUser().getId();
        List<Home> homeList = userService.getHome(UserId);
        return Result.success(homeList);
    }

    /**
     * 添加房间
     * @param room
     * @return
     */
    @PostMapping("/addRoom")
    public Result addRoom(@RequestBody Room room) {
        log.info("添加房间：{}",room.getRoomName());
        return userService.addRoom(room);
    }

    @GetMapping("/getRoom")
    public Result<List<Room>> getRoom(){
        int UserId = UserHolder.getUser().getId();
        return userService.getRooms(UserId);
    }
}
